package cn.com.jsr.translation.termidentifier;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 术语字典。
 * 注：所有添加进来的术语均将合并连续的多个空白字符为单个空格
 */
public class Dictionary{
	private static Logger logger = LoggerFactory.getLogger(Dictionary.class);
	
	protected Properties dict = new Properties();
	
	/**
	 * 获取指定的术语对应的翻译
	 * @param term 英文术语
	 * @return
	 */
	public String get(String term){
		return dict.getProperty(term.replaceAll("\\s+", " "));
	}
	
	/**
	 * 添加/修改术语字典
	 * @param term 英文术语
	 * @param translation 中文翻译
	 */
	public void set(String term, String translation){
		dict.setProperty(term.replaceAll("\\s+", " "), translation);
	}
	
	/**
	 * 删除指定的术语翻译
	 * @param term 英文术语
	 */
	public void remove(String term){
		dict.remove(term.replaceAll("\\s+", " "));
	}
	
	/**
	 * 判定给定的术语是否存在
	 * @param term 英文术语
	 * @return
	 */
	public boolean has(String term){
		return dict.containsKey(term.replaceAll("\\s+", " "));
	}
	
	/**
	 * 合并字典
	 * @param dict 要合并的字典
	 */
	public void merge(Dictionary dictionary){
		List<String> terms = dictionary.listTerms();
		for(String term: terms)
			this.set(term, dictionary.get(term));
	}
	
	/**
	 * 获取字典的英文术语列表
	 * @return
	 */
	public List<String> listTerms(){
		List<String> list = new ArrayList<>();
		Enumeration<String> terms = (Enumeration<String>) dict.propertyNames();
		while(terms.hasMoreElements())
			list.add(terms.nextElement());
		
		return list;
	}
	
	
	/**
	 * 从文本输入流中读取字典。文本流格式：
	 * term = translation，如：“term = 术语”。多个术语之间换行分割。
	 * @param is 文本输入流
	 * @return
	 */
	public static Dictionary load(InputStream is){
		try(BufferedReader br = new BufferedReader(new InputStreamReader(is));){
			Dictionary dictionary = new Dictionary();
			
			String line = "";
			while((line = br.readLine()) != null){
				String[] segs = line.split("\\s*=\\s*");
				if(segs.length < 2)
					continue;
				
				dictionary.set(segs[0].trim(), segs[1].trim());
			}
			
			return dictionary;
		}catch(IOException e){
			logger.error("Error occured while loading dictionary", e);
		}
		
		return null;
	}
	
	/**
	 * 从给定的文本中读取字典。文本流格式：
	 * [term][blanks][translation]
	 * @param origin 字典文本
	 * @return
	 */
	public static Dictionary load(String origin){
		return load(new ByteArrayInputStream(origin.getBytes()));
	}
}
